package com.liugang.oss_demo.controller;

import com.liugang.oss_demo.util.OSSUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
public class OssController {

    //错误用法 不能用File.separator
    //private static final String filePath = "path" + File.separator + "test";

    private final String basePath = "path/test/";

    @PostMapping("/uploadFile")
    public void uploadFile(MultipartFile file){
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        String fileName = UUID.randomUUID().toString().replace("-", "");

        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex > 0) {
            fileExtension = originalFilename.substring(dotIndex); // 包括点号
        }

        String newFileName = fileName + fileExtension;
        String newFilePath = basePath + newFileName;

        System.out.println(newFilePath);
        System.out.println(newFileName);

        OSSUtil.upload(file, newFilePath);

    }

    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response){

        //4fc530b2cc4045fca612d35fdc238dcd.jpeg
        String ossFilePath = basePath + fileName;
        OSSUtil.download(ossFilePath, fileName, response);

    }

    @GetMapping("/delete")
    public void delete(String fileName){

        //4fc530b2cc4045fca612d35fdc238dcd.jpeg
        String ossFilePath = basePath + fileName;
        OSSUtil.deleteFile(ossFilePath);
    }

}
